package com.bolt.support.spring.mvc.resolver;

import com.bolt.common.utils.JacksonUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.google.common.io.ByteSource;
import org.springframework.web.context.request.NativeWebRequest;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ResolverUtil {

    private static final String JSON_REQUEST_ATTRIBUTE_NAME = "JSON_REQUEST_BODY";


    public static JsonNode getJsonBody(final NativeWebRequest nativeWebRequest) {
        final ContentCachingRequestWrapper servletRequest = nativeWebRequest.getNativeRequest(
                ContentCachingRequestWrapper.class
        );


        JsonNode body = (JsonNode) nativeWebRequest.getAttribute(
                JSON_REQUEST_ATTRIBUTE_NAME,
                NativeWebRequest.SCOPE_REQUEST
        );

        if (body == null) {
            try {
                if (servletRequest != null) {

                    String read = ByteSource.wrap(servletRequest.getContentAsByteArray())
                            .asCharSource(StandardCharsets.UTF_8).read(); // Please note

                    body = JacksonUtil.getObjectMapper().readTree(read);
                }
            } catch (final IOException e) {
                //
            }
            if (body == null) {
                body = NullNode.getInstance();
            }
            nativeWebRequest.setAttribute(
                    JSON_REQUEST_ATTRIBUTE_NAME,
                    body,
                    NativeWebRequest.SCOPE_REQUEST
            );
        }
        return body;
    }
}